/*
 * Copyright (c) 2020. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
 * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan.
 * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna.
 * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus.
 * Vestibulum commodo. Ut rhoncus gravida arcu.
 */

package com.shide.businessuser.mvvm.view;

import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.shide.businessuser.R;
import com.shide.businessuser.UI.PopWinUtils;
import com.shide.businessuser.Utils.FuctionUtils;
import com.shide.businessuser.Utils.LogUtil;
import com.shide.businessuser.Utils.MessageEvent;
import com.shide.businessuser.http.GlobleURL;
import com.shide.businessuser.http.GsonUtils;
import com.shide.businessuser.http.OkhttpUtils;
import com.shide.businessuser.http.ParJson;
import com.shide.businessuser.http.entity.ErrorInfo;
import com.shide.businessuser.http.entity.Product;
import com.shide.businessuser.http.entity.exchargeInfo;
import com.shide.businessuser.mvvm.model.Product_mvvm;

import org.greenrobot.eventbus.EventBus;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.Response;

public class PopWin_UpShelf_goods_mvvm extends PopupWindow {
    private Button btnDeleteGoods;
    private Button btnUpShelf;
    private Button btnSure;
    private Button btnCancel;
    private Context mContext;
    private Button btn_back_scan;
    private Product_mvvm product;
    public Product_mvvm getProduct() {
        return product;
    }

    public void setProduct(Product_mvvm product) {
        this.product = product;
    }



    public PopWin_UpShelf_goods_mvvm(Context context) {
        super(context);
        mContext = context;
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        final View view = inflater.inflate(R.layout.popwin_up_shelf_product, null);
        // 设置SelectPicPopupWindow的View
        this.setContentView(view);
        PopWinUtils.setBasicStyle(context,this);
        initView(view);

    }



    private void initView(View view) {
        btnDeleteGoods = (Button) view.findViewById(R.id.btn_deleteGoods);
        btnUpShelf = (Button) view.findViewById(R.id.btn_up_shelf);
        ImageView img_cancel= view.findViewById(R.id.imageView_cancel);
        img_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
        btnDeleteGoods.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                    deleteGoods();
                }
            });

        btnUpShelf.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    upGoods();
                }
            });
}




    /**
      * 显示popupWindow
      * @param parent
      */
    public void showPopupWindow(View parent) {
        if (!this.isShowing()) {
            this.showAtLocation(parent, Gravity.CENTER, 0, 0);
        } else {
            this.dismiss();
        }
    }

    /**
     * 上架商品
     *
     */
    private void upGoods() {
        if (product != null) {
            FormBody.Builder builder = new FormBody.Builder();
            builder.add("id", product.getId());
            builder.add("shelf", "1");

            OkhttpUtils.post_token_Json(GlobleURL.UpOrDownShelf, builder, new Callback() {
                @Override
                public void onFailure(@NotNull Call call, @NotNull IOException e) {

                    ((Activity)mContext).runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            LogUtil.e("PopWin_UpShelf_goods.this",e.getMessage());
                            Toast.makeText(mContext, "请检查网络", Toast.LENGTH_SHORT).show();
                            dismiss();
                        }
                    });
                }

                @Override
                public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                    String json = response.body().string();
                    Boolean error = ParJson.isError(json);

                    if (response.code() == 401){
                        FuctionUtils.BackLogin(response,mContext);
                        return;
                    }

                    if (error) {
                        ErrorInfo errorData = ParJson.getErrorData(json);
                        ((Activity)mContext).runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                LogUtil.e("PopWin_upShelf_goods",errorData.getMessage());
                               // Toast.makeText(mContext, errorData.getMessage(), Toast.LENGTH_SHORT).show();
                               // FuctionUtils.BackLogin(response,mContext);
                                dismiss();
                            }
                        });

                    }else{
                        exchargeInfo ei = GsonUtils.JsonToObject(json, exchargeInfo.class);
                        if (ei != null) {
                            if (ei.getCode().equals("200")){
                                MessageEvent messageEvent = new MessageEvent();
                                messageEvent.setCode(MessageEvent.UP_DOWN_GOODS);
                                EventBus.getDefault().post(messageEvent);
                                handler.sendEmptyMessage(0);
                            }
                            ((Activity)mContext).runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(mContext, ei.getMsg(), Toast.LENGTH_SHORT).show();
                                }
                            });
                        }

                    }
                }
            });
        }
    }

    /**
     * 删除商品
     */
    private void deleteGoods(){
        if (product != null) {

            HttpUrl.Builder urlBuilder = HttpUrl.parse(GlobleURL.DeletGoods).newBuilder();
            urlBuilder.addQueryParameter("id",product.getId());


            OkhttpUtils.delete(urlBuilder, new Callback() {
                @Override
                public void onFailure(@NotNull Call call, @NotNull IOException e) {
                    ((Activity)mContext).runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            LogUtil.e("PopWin_UpShelf.this",e.getMessage());
                            Toast.makeText(mContext, "请检查网络", Toast.LENGTH_SHORT).show();
                            dismiss();
                        }
                    });
                }

                @Override
                public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                    String json = response.body().string();
                    Boolean error = ParJson.isError(json);
                    if (response.code() == 401){
                        FuctionUtils.BackLogin(response,mContext);
                        return;
                    }

                    if (error) {
                        ErrorInfo errorData = ParJson.getErrorData(json);
                        ((Activity)mContext).runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                LogUtil.e("PopWin_upshelf",errorData.getMessage());
                               // Toast.makeText(mContext, errorData.getMessage(), Toast.LENGTH_SHORT).show();
                               // FuctionUtils.BackLogin(response,mContext);
                                dismiss();
                            }
                        });

                    }else{
                        exchargeInfo ei = GsonUtils.JsonToObject(json, exchargeInfo.class);
                        if (ei != null) {
                           if (ei.getCode().equals("200")){
                               MessageEvent messageEvent = new MessageEvent();
                               messageEvent.setCode(MessageEvent.UP_DOWN_GOODS);
                               EventBus.getDefault().post(messageEvent);
                               handler.sendEmptyMessage(0);
                           }
                            ((Activity)mContext).runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(mContext, ei.getMsg(), Toast.LENGTH_SHORT).show();
                                }
                            });
                        }

                    }
                }
            });
        }


    }

    Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0){
                dismiss();
            }
        }
    };


}
